<?php
namespace Anker1992\BasicLib;

class HttpRequestClient
{
    private $headers; //请求头
    private $connectTimeout; //连接超时
    private $socketTimeout; //响应超时
    private $conf; //预处理配置

    /**
     * 构造函数
     * @param array $headers 请求头，例如：
     * array(’content-type‘=> 'application/json', 'connection' => 'keep-alive')
     */
    public function __construct($headers = array())
    {
        $this->headers = $this->buildHeaders($headers);
        $this->connectTimeout = 60000;
        $this->socketTimeout = 60000;
        $this->conf = array();
    }

    /**
     * 设置连接超时
     * @param int $ms 毫秒
     */
    public function setConnectionTimeoutInMillis($ms)
    {
        $this->connectTimeout = $ms;
    }

    /**
     * 设置响应超时
     * @param int $ms 毫秒
     */
    public function setSocketTimeoutInMillis($ms)
    {
        $this->socketTimeout = $ms;
    }

    /**
     * 预处理配置
     * @param array $conf
     */
    public function setConf($conf){
        $this->conf = $conf;
    }

    /**
     * 请求预处理
     * @param resource $ch
     */
    public function prepare($ch)
    {
        foreach($this->conf as $key => $value) {
            curl_setopt($ch, $key, $value);
        }
    }

    /**
     * 构造header
     * @param array $headers
     * @return array
     */
    private function buildHeaders($headers)
    {
        $result = array();
        foreach($headers as $k => $v) {
            $result[] = sprintf("%s:%s", $k, $v);
        }
        return $result;
    }

    /**
     * 构造url
     * @param string $url
     * @param array $params
     * @return string
     */
    private function buildUrl($url, $params)
    {
        if (!empty($params)) {
            $str = http_build_query($params);
            return $url. (strpos($url, "?") === false ? "?" : "&"). $str;
        } else {
            return $url;
        }
    }

    /**
     * curl模拟get请求
     * @param string $url
     * @param array $params get参数
     * @param array $headers header参数
     * @return array
     */
    public function get($url, $params = array(), $headers = array())
    {
        $url = $this->buildUrl($url, $params);
        $headers = array_merge($this->headers, $this->buildHeaders($headers));

        $ch = curl_init();
        $this->prepare($ch);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false); //设置是否输出响应头
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //curl_exec后结果以文件流形式返回，而不是直接输出，可以用变量接受
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); //设置请求头
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, $this->socketTimeout); //设置响应超时
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $this->connectTimeout); //设置连接超时
        $content = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($code === 0) {
            throw new \Exception(curl_error($ch));
        }

        curl_close($ch);
        return array(
            'code' => $code,
            'content' => $content
        );
    }

    /**
     * curl模拟post请求
     * @param string $url
     * @param array $data post参数
     * @param array $params get参数
     * @param array $headers header参数
     * @return array
     */
    public function post($url, $data = array(), $params = array(), $headers = array())
    {
        $url = $this->buildUrl($url, $params);
        $headers = array_merge($this->headers, $this->buildHeaders($headers));

        $ch = curl_init();
        $this->prepare($ch);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($data) ? http_build_query($data) : $data);
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, $this->socketTimeout);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $this->connectTimeout);
        $content = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if($code === 0){
            throw new \Exception(curl_error($ch));
        }

        curl_close($ch);
        return array(
            'code' => $code,
            'content' => $content,
        );
    }
}